class Solution {
public:
    bool isValid(string s) {
        for (int i = 0; i < s.size(); i++) {
            if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
                s1.push(s[i]);
            }
            else {
                if (i == 0) return false;
                switch (s[i]) {
                    case ')':
                        if (!s1.empty() && s1.top() == '(') s1.pop(); 
                        else return false;
                        break;
                    case ']':
                        if (!s1.empty() && s1.top() == '[') s1.pop(); 
                        else return false;
                        break;
                    case '}':
                        if (!s1.empty() && s1.top() == '{') s1.pop(); 
                        else return false;
                        break;
                }
            }
        }
        if (s1.empty()) return true;
        return false;
    }
private:    
    stack<char> s1;
};